#include "toolbar.h" 
#include "winassert.h"

namespace win
{
Toolbar::Toolbar()
{
	_bar_height = 0;
}

Toolbar::~Toolbar()
{
	
}

void Toolbar::Create(Window &parent, const int child_index)
{
	HINSTANCE hinst = parent.AppInstance();
   _hwnd = CreateWindowEx(0, TOOLBARCLASSNAME, (LPSTR) NULL,
        WS_CHILD | CCS_ADJUSTABLE | TBSTYLE_FLAT,
        0, 0, 0, 0, parent.GetHandle(), (HMENU) child_index,
    	hinst, NULL);
   SendMessage(_hwnd, TB_BUTTONSTRUCTSIZE,
        (WPARAM) sizeof(TBBUTTON), 0);
    TBADDBITMAP tbab;
	tbab.hInst = HINST_COMMCTRL;
    tbab.nID   = IDB_STD_SMALL_COLOR;
    SendMessage(_hwnd, TB_ADDBITMAP, 0,
        (WPARAM) &tbab);

	RECT r;
	GetWindowRect(r);
	_bar_height = r.bottom - r.top;
}

void Toolbar::AddWindowsButton(const win_button btn,
							   int command_id,
          					   bool enabled )
{
	TBBUTTON tbtn;
	tbtn.iBitmap = static_cast<int> (btn);
	tbtn.idCommand = command_id;
	tbtn.fsState = enabled?TBSTATE_ENABLED:0;
	tbtn.fsStyle = TBSTYLE_BUTTON;
	tbtn.dwData = 0;
	tbtn.iString = 0;
 	::SendMessage(_hwnd,TB_ADDBUTTONS,1,(LPARAM) &tbtn);
}

void Toolbar::AddResourceButtons(unsigned int resId, 
					 	const std::vector<int> &commandIds)
{

	HBITMAP hbmp = (HBITMAP) 
 			LoadImage(AppInstance(),MAKEINTRESOURCE(resId),IMAGE_BITMAP,0,0,
    				LR_LOADMAP3DCOLORS);
	ASSERT(hbmp != NULL);
	TBADDBITMAP bmp;
	bmp.hInst = NULL;
	bmp.nID =  (UINT) hbmp;
	::SendMessage(_hwnd, TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON),0);
 	int result = ::SendMessage(_hwnd, TB_ADDBITMAP,	(WPARAM) commandIds.size(), (LPARAM) &bmp); 
 	ASSERT(result != -1);
 	TBBUTTON btn;
 	ZeroMemory(&btn,sizeof(btn));
	btn.fsState = TBSTATE_ENABLED;
	btn.fsStyle = TBSTYLE_BUTTON;
	btn.dwData = 0;
	btn.iString = 0;
 	for (size_t i = 0; i < commandIds.size(); i++ )
 	{
		btn.iBitmap = result + i;
		btn.idCommand = commandIds[i];
 		::SendMessage(_hwnd, TB_ADDBUTTONS, 1, (LPARAM) &btn);
	}
}

void Toolbar::SetButtonState(int commandId, bool enabled)
{
	WORD state = enabled?TBSTATE_ENABLED:0;
	::SendMessage(_hwnd,TB_SETSTATE,commandId,MAKELONG(state,0));
}

void Toolbar::AddSeperator()
{
	TBBUTTON btn;
 	::ZeroMemory(&btn,sizeof(btn));
	btn.fsState = TBSTATE_ENABLED;
	btn.fsStyle = TBSTYLE_SEP;
 	::SendMessage(_hwnd,TB_ADDBUTTONS,1,(LPARAM) &btn);
}
}
